package com.example.qaplatform.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.example.qaplatform.entity.ChatEntity;
import com.example.qaplatform.entity.History1Entity;
import com.example.qaplatform.entity.ImageEntity;
import com.example.qaplatform.repository.ChatRepository;
import com.example.qaplatform.repository.History1Repository;
import com.example.qaplatform.repository.ImageRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.http.HttpMethod;

@RestController
@RequestMapping("/api/chat")
public class ChatController {
    @Autowired
    private ChatRepository chatRepository;
    @Autowired
    private History1Repository history1Repository;
    @Autowired
    private ImageRepository imageRepository;

    @Value("${ragflow.api.key}")
    private String ragflowApiKey;

    @Value("${ragflow.dataset.id}")
    private String datasetId;

    // 1. 创建会话
    @PostMapping("/create")
    public ChatEntity createChat(@RequestBody Map<String, Object> req) {
        Long userId = Long.valueOf(req.get("userId").toString());
        String title = req.get("title").toString();
        ChatEntity chat = new ChatEntity();
        chat.setUserId(userId);
        chat.setTitle(title);
        chat.setCreateTime(LocalDateTime.now());
        return chatRepository.save(chat);
    }

    // 2. 查询用户所有会话
    @GetMapping("/list/{userId}")
    public List<ChatEntity> listChats(@PathVariable Long userId) {
        return chatRepository.findByUserIdOrderByCreateTimeDesc(userId);
    }

    // 3. 查询某会话下所有消息
    @GetMapping("/history/{chatId}")
    public List<History1Entity> listHistory(@PathVariable Long chatId) {
        return history1Repository.findByChatIdOrderByCreateTimeAsc(chatId);
    }

    // 4. 发送消息（保存到history1）
    @PostMapping(value = "/send", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ChatMessageDTO sendMessage(
            @RequestPart("data") String data,
            @RequestPart(value = "image0", required = false) MultipartFile image0) {
        // 反序列化data
        List<String> imageIdList = new ArrayList<>();
        Map<String, Object> req;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            req = objectMapper.readValue(data, Map.class);
        } catch (Exception e) {
            throw new RuntimeException("参数解析失败");
        }
        Long chatId = Long.valueOf(req.get("chatId").toString());
        Long userId = Long.valueOf(req.get("userId").toString());
        String question = req.get("question").toString();

        String imageUrl = null;
        ImageEntity saved = null;
        String docId = null;
        String ocrText = null;
        String imageId = null;
        String answer = "";

        // 自动将第一条消息内容设置为chat标题（如果还没有标题）
        Optional<ChatEntity> chatOpt = chatRepository.findById(chatId);
        if (chatOpt.isPresent()) {
            ChatEntity chat = chatOpt.get();
            if (chat.getTitle() == null || chat.getTitle().trim().isEmpty()) {
                String title = question.length() > 20 ? question.substring(0, 20) : question;
                chat.setTitle(title);
                chatRepository.save(chat);
            }
        }

        // 有图片上传分支
        if (image0 != null && !image0.isEmpty()) {
            try {
                ImageEntity entity = new ImageEntity();
                entity.setName(image0.getOriginalFilename());
                entity.setContentType(image0.getContentType());
                entity.setData(image0.getBytes());
                entity.setCreateTime(LocalDateTime.now());
                saved = imageRepository.save(entity);
                imageUrl = "/api/chat/image/" + saved.getId();
            } catch (Exception e) {
                throw new RuntimeException("图片保存到本地数据库失败", e);
            }
            try {
                String uploadUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents";
                HttpHeaders uploadHeaders = new HttpHeaders();
                uploadHeaders.set("Authorization", "Bearer " + ragflowApiKey);
                uploadHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
                MultiValueMap<String, Object> uploadBody = new LinkedMultiValueMap<>();
                uploadBody.add("file", new ByteArrayResource(image0.getBytes()) {
                    @Override
                    public String getFilename() {
                        return image0.getOriginalFilename();
                    }
                });
                HttpEntity<MultiValueMap<String, Object>> uploadEntity = new HttpEntity<>(uploadBody, uploadHeaders);
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<Map> uploadResp = restTemplate.postForEntity(uploadUrl, uploadEntity, Map.class);
                Object dataObj = uploadResp.getBody().get("data");
                if (dataObj instanceof Map) {
                    Object idObj = ((Map) dataObj).get("id");
                    if (idObj != null) docId = idObj.toString();
                    Object contentObj = ((Map) dataObj).get("content");
                    if (contentObj != null) ocrText = contentObj.toString();
                } else if (dataObj instanceof List && !((List) dataObj).isEmpty()) {
                    Object first = ((List) dataObj).get(0);
                    if (first instanceof Map) {
                        Object idObj = ((Map) first).get("id");
                        if (idObj != null) docId = idObj.toString();
                    }
                }
                if (docId != null) {
                    saved.setDocId(docId);
                    imageRepository.save(saved);
                    // 新增：优先用文件名查ragflow描述
                    String filename = image0.getOriginalFilename();
                    String imageDescription = "";
                    if (filename != null) {
                        String nameWithoutExt = filename.contains(".") ? filename.substring(0, filename.lastIndexOf('.')) : filename;
                        // 新增：去掉下划线、连字符及后缀数字，只保留建筑名部分
                        String cleanName = nameWithoutExt.replaceAll("[_\\-][0-9]+$", ""); // 去掉如 _1、-2 结尾
                        System.out.println("[文件名处理] 原始文件名: " + filename);
                        System.out.println("[文件名处理] 去除扩展名后: " + nameWithoutExt);
                        System.out.println("[文件名处理] 清洗后建筑名: " + cleanName);
                        if (cleanName.contains("_")) {
                            cleanName = cleanName.substring(0, cleanName.indexOf("_"));
                            System.out.println("[文件名处理] 截取下划线前: " + cleanName);
                        }
                        if (cleanName.contains("-")) {
                            cleanName = cleanName.substring(0, cleanName.indexOf("-"));
                            System.out.println("[文件名处理] 截取连字符前: " + cleanName);
                        }
                        if (cleanName.contains("桥") || cleanName.contains("亭")) {
                            // 直接用关键词作为问题，调用ragflow聊天API
                            String chatIdForRagflow = "a9d603b05e2b11f0ab2f0242ac120006"; // 请替换为你的知识库chatId
                            String apiUrl = "http://localhost/api/v1/chats_openai/" + chatIdForRagflow + "/chat/completions";
                            HttpHeaders headers = new HttpHeaders();
                            headers.set("Authorization", "Bearer " + ragflowApiKey);
                            headers.setContentType(MediaType.APPLICATION_JSON);
                            Map<String, Object> payload = new HashMap<>();
                            payload.put("model", "qwen2.5vl:3b");
                            List<Map<String, Object>> messages = new ArrayList<>();
                            Map<String, Object> userMsg = new HashMap<>();
                            userMsg.put("role", "user");
                            userMsg.put("content", "请介绍“" + cleanName + "”。");
                            messages.add(userMsg);
                            payload.put("messages", messages);
                            payload.put("stream", false);
                            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);
                            try {
                                ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, entity, Map.class);
                                if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                                    Object choices = response.getBody().get("choices");
                                    if (choices instanceof List && !((List) choices).isEmpty()) {
                                        Object first = ((List) choices).get(0);
                                        if (first instanceof Map) {
                                            Map firstMap = (Map) first;
                                            Object message = firstMap.get("message");
                                            if (message instanceof Map) {
                                                Map msgMap = (Map) message;
                                                Object contentObj = msgMap.get("content");
                                                if (contentObj != null) imageDescription = contentObj.toString();
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    if (imageDescription == null || imageDescription.isEmpty()) {
                        // 文件名没有命中，走Ollama生成描述
                        String base64Image = Base64.getEncoder().encodeToString(image0.getBytes());
                        Map<String, Object> ollamaBody = new HashMap<>();
                        ollamaBody.put("model", "qwen2.5vl:3b");
                        ollamaBody.put("prompt", "请用中文详细描述这张图片的内容。");
                        ollamaBody.put("images", List.of(base64Image));
                        HttpHeaders ollamaHeaders = new HttpHeaders();
                        ollamaHeaders.setContentType(MediaType.APPLICATION_JSON);
                        HttpEntity<Map<String, Object>> ollamaEntity = new HttpEntity<>(ollamaBody, ollamaHeaders);
                        StringBuilder descBuilder = new StringBuilder();
                        try {
                            ResponseEntity<String> ollamaResp = restTemplate.postForEntity("http://localhost:11434/api/generate", ollamaEntity, String.class);
                            byte[] bytes = ollamaResp.getBody().getBytes(StandardCharsets.ISO_8859_1);
                            String utf8Body = new String(bytes, StandardCharsets.UTF_8);
                            String[] lines = utf8Body.split("\\r?\\n");
                            ObjectMapper mapper = new ObjectMapper();
                            for (String line : lines) {
                                if (!line.trim().isEmpty()) {
                                    Map<String, Object> json = mapper.readValue(line.trim(), Map.class);
                                    if (json.get("response") != null) {
                                        descBuilder.append(json.get("response").toString());
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        imageDescription = descBuilder.toString().trim();
                        if (imageDescription.isEmpty()) {
                            imageDescription = "图片分块";
                        }
                    }
                    // 2. ragflow分块
                    String chunkUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents/" + docId + "/chunks";
                    HttpHeaders chunkHeaders = new HttpHeaders();
                    chunkHeaders.set("Authorization", "Bearer " + ragflowApiKey);
                    chunkHeaders.setContentType(MediaType.APPLICATION_JSON);
                    Map<String, Object> chunkBody = new HashMap<>();
                    chunkBody.put("content", imageDescription);
                    HttpEntity<Map<String, Object>> chunkEntity = new HttpEntity<>(chunkBody, chunkHeaders);
                    ResponseEntity<Map> chunkResp = restTemplate.postForEntity(chunkUrl, chunkEntity, Map.class);
                    if (chunkResp.getBody() != null && chunkResp.getBody().get("data") != null) {
                        Object chunkDataObj = chunkResp.getBody().get("data");
                        if (chunkDataObj instanceof Map) {
                            Object chunksObj = ((Map) chunkDataObj).get("chunks");
                            if (chunksObj instanceof List && !((List) chunksObj).isEmpty()) {
                                Object firstChunk = ((List) chunksObj).get(0);
                                if (firstChunk instanceof Map) {
                                    Object imageIdObj = ((Map) firstChunk).get("image_id");
                                    if (imageIdObj != null) {
                                        imageId = imageIdObj.toString();
                                    }
                                }
                            }
                        }
                    }
                }
                // ragflow主回答
                String chatIdForRagflow = "a9d603b05e2b11f0ab2f0242ac120006";
                String apiUrl = "http://localhost/api/v1/chats_openai/" + chatIdForRagflow + "/chat/completions";
                HttpHeaders headers = new HttpHeaders();
                headers.set("Authorization", "Bearer " + ragflowApiKey);
                headers.setContentType(MediaType.APPLICATION_JSON);
                Map<String, Object> payload = new HashMap<>();
                payload.put("model", "qwen2.5vl:3b");
                List<Map<String, Object>> messages = new ArrayList<>();
                Map<String, Object> userMsg = new HashMap<>();
                userMsg.put("role", "user");
                userMsg.put("content", question);
                if (docId != null && !docId.isEmpty()) {
                    List<String> docIds = new ArrayList<>();
                    docIds.add(docId);
                    userMsg.put("doc_ids", docIds);
                }
                messages.add(userMsg);
                payload.put("messages", messages);
                payload.put("stream", false);
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);
                ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, entity, Map.class);
                String content = "";
                if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                    Object choices = response.getBody().get("choices");
                    if (choices instanceof List && !((List) choices).isEmpty()) {
                        Object first = ((List) choices).get(0);
                        if (first instanceof Map) {
                            Map firstMap = (Map) first;
                            Object message = firstMap.get("message");
                            if (message instanceof Map) {
                                Map msgMap = (Map) message;
                                Object contentObj = msgMap.get("content");
                                if (contentObj != null) content = contentObj.toString();
                                Object docIdsObj = msgMap.get("doc_ids");
                                if (docIdsObj instanceof List) {
                                    for (Object id : (List) docIdsObj) {
                                        if (id != null) imageIdList.add(id.toString());
                                    }
                                }
                            }
                        }
                    }
                }
                // 替换[ID:x]为图片URL
                Map<String, String> idMap = new HashMap<>();
                for (int i = 0; i < imageIdList.size(); i++) {
                    idMap.put(String.valueOf(i), imageIdList.get(i));
                }
                Pattern pattern = Pattern.compile("\\[ID:(\\d+)\\]");
                Matcher matcher = pattern.matcher(content);
                StringBuffer sb = new StringBuffer();
                while (matcher.find()) {
                    String num = matcher.group(1);
                    String imageIdVal = idMap.getOrDefault(num, "");
                    String imgTag = "";
                    if (!imageIdVal.isEmpty()) {
                        imgTag = "<br><img src='http://localhost/v1/document/image/" + imageIdVal + "' style='width:200px; border-radius:8px; margin:8px 0;' />";
                    }
                    matcher.appendReplacement(sb, Matcher.quoteReplacement(imgTag));
                }
                matcher.appendTail(sb);
                answer = sb.length() > 0 ? sb.toString() : content;
               System.out.println("[图片分支] ragflow返回content: " + content);
               System.out.println("[图片分支] ragflow返回imageIdList: " + imageIdList);
               System.out.println("[图片分支] answer: " + answer);
               System.out.println("[图片分支] docId: " + docId);
            } catch (Exception e) {
                answer = "后端异常: " + e.getMessage();
            }
        } else if (question != null && !question.isEmpty()) { // 无图片，仅文本分支
            try {
                // 1. ragflow主回答
                RestTemplate restTemplate = new RestTemplate();
                String chatIdForRagflow = "a9d603b05e2b11f0ab2f0242ac120006";
                String apiUrl = "http://localhost/api/v1/chats_openai/" + chatIdForRagflow + "/chat/completions";
                HttpHeaders headers = new HttpHeaders();
                headers.set("Authorization", "Bearer " + ragflowApiKey);
                headers.setContentType(MediaType.APPLICATION_JSON);
                Map<String, Object> payload = new HashMap<>();
                payload.put("model", "qwen2.5vl:3b");
                List<Map<String, Object>> messages = new ArrayList<>();
                Map<String, Object> userMsg = new HashMap<>();
                userMsg.put("role", "user");
                userMsg.put("content", question);
                messages.add(userMsg);
                payload.put("messages", messages);
                payload.put("stream", false);
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);
                ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, entity, Map.class);
                String ragflowContent = "";
                if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                    Object choices = response.getBody().get("choices");
                    if (choices instanceof List && !((List) choices).isEmpty()) {
                        Object first = ((List) choices).get(0);
                        if (first instanceof Map) {
                            Map firstMap = (Map) first;
                            Object message = firstMap.get("message");
                            if (message instanceof Map) {
                                Map msgMap = (Map) message;
                                Object contentObj = msgMap.get("content");
                                if (contentObj != null) ragflowContent = contentObj.toString();
                            }
                        }
                    }
                }
                // 1.5 用ollama大模型提取关键词
                String extractedKeywords = "";
                try {
                    String prompt = "请提取下面句子的检索关键词，返回最相关的1-2个词，用逗号分隔：" + question;
                    Map<String, Object> ollamaBody = new HashMap<>();
                    ollamaBody.put("model", "qwen2.5vl:3b");
                    ollamaBody.put("prompt", prompt);
                    HttpHeaders ollamaHeaders = new HttpHeaders();
                    ollamaHeaders.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<Map<String, Object>> ollamaEntity = new HttpEntity<>(ollamaBody, ollamaHeaders);
                    ResponseEntity<String> ollamaResp = restTemplate.postForEntity("http://localhost:11434/api/generate", ollamaEntity, String.class);
                    // 处理ollama返回的流式结果
                    StringBuilder keywordsBuilder = new StringBuilder();
                    byte[] bytes = ollamaResp.getBody().getBytes(java.nio.charset.StandardCharsets.ISO_8859_1);
                    String utf8Body = new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
                    String[] lines = utf8Body.split("\\r?\\n");
                    ObjectMapper mapper = new ObjectMapper();
                    for (String line : lines) {
                        if (!line.trim().isEmpty()) {
                            Map<String, Object> json = mapper.readValue(line.trim(), Map.class);
                            if (json.get("response") != null) {
                                keywordsBuilder.append(json.get("response").toString());
                            }
                        }
                    }
                    extractedKeywords = keywordsBuilder.toString().replaceAll("[\r\n]", "").trim();
                    // 只取第一个逗号前的关键词（如有多个）
                    if (extractedKeywords.contains("，")) {
                        extractedKeywords = extractedKeywords.split("，")[0];
                    } else if (extractedKeywords.contains(",")) {
                        extractedKeywords = extractedKeywords.split(",")[0];
                    }
                } catch (Exception e) {
                    extractedKeywords = "";
                }
                //System.out.println("[文本分支] 提取到的关键词: " + extractedKeywords);
                // 2. 先用列出文档API查找图片文档
                //String encodedKeywords = URLEncoder.encode(extractedKeywords, "UTF-8");
                String docListUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents?page=1&page_size=30&orderby=create_time&desc=booleantrue&keywords=" + extractedKeywords;
                System.out.println("[文本分支] 请求文档API的URL: " + docListUrl);
                HttpHeaders docHeaders = new HttpHeaders();
                docHeaders.set("Authorization", "Bearer " + ragflowApiKey);
                HttpEntity<String> httpEntity = new HttpEntity<>(docHeaders);

                ResponseEntity<Map> docListResp = restTemplate.exchange(
                    docListUrl,
                    HttpMethod.GET,
                    httpEntity,
                    Map.class
                );
                List<String> docIdList = new ArrayList<>();
                //System.out.println("[DEBUG] 文档API原始返回: " + docListResp.getBody());
                if (docListResp.getStatusCode() == HttpStatus.OK && docListResp.getBody() != null) {
                    Object dataObj = docListResp.getBody().get("data");
                    System.out.println("[DEBUG] dataObj: " + dataObj);
                    if (dataObj instanceof Map) {
                        Object docsObj = ((Map) dataObj).get("docs");
                        System.out.println("[DEBUG] docsObj: " + docsObj);
                        if (docsObj instanceof List) {
                            List docs = (List) docsObj;
                            for (Object docObj : docs) {
                                if (docObj instanceof Map) {
                                    String chunkMethod = ((Map) docObj).getOrDefault("chunk_method", "").toString();
                                    String docIdVal = ((Map) docObj).getOrDefault("id", "").toString();
                                    if ("picture".equals(chunkMethod) && !docIdVal.isEmpty()) {
                                        docIdList.add(docIdVal);
                                    }
                                }
                            }
                        }
                    }
                }
                // 3. 用docIdList查块，提取image_id
                List<String> retrievedImageIdList = new ArrayList<>();
                for (String docIdPic : docIdList) {
                    String chunkListUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents/" + docIdPic + "/chunks?keywords=&page=1&page_size=10";
                    HttpHeaders chunkHeaders = new HttpHeaders();
                    chunkHeaders.set("Authorization", "Bearer " + ragflowApiKey);
                    HttpEntity<String> chunkHttpEntity = new HttpEntity<>(chunkHeaders);

                    ResponseEntity<Map> chunkListResp = restTemplate.exchange(
                        chunkListUrl,
                        HttpMethod.GET,
                        chunkHttpEntity,
                        Map.class
                    );
                    if (chunkListResp.getStatusCode() == HttpStatus.OK && chunkListResp.getBody() != null) {
                        Object dataObj = chunkListResp.getBody().get("data");
                        if (dataObj instanceof Map) {
                            Object chunksObj = ((Map) dataObj).get("chunks");
                            if (chunksObj instanceof List) {
                                List chunks = (List) chunksObj;
                                for (Object chunkObj : chunks) {
                                    if (chunkObj instanceof Map) {
                                        String imageIdVal = ((Map) chunkObj).getOrDefault("image_id", "").toString();
                                        if (!imageIdVal.isEmpty()) {
                                            retrievedImageIdList.add(imageIdVal);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // 4. 替换ragflowContent中的[ID:x]，动态编号映射
                // 先统计ragflowContent里所有[ID:x]出现顺序
                List<String> idOrder = new ArrayList<>();
                Pattern pattern = Pattern.compile("\\[ID:(\\d+)\\]");
                Matcher matcher = pattern.matcher(ragflowContent);
                while (matcher.find()) {
                    String num = matcher.group(1);
                    if (!idOrder.contains(num)) {
                        idOrder.add(num);
                    }
                }
                // 构建映射
                Map<String, String> idMap = new HashMap<>();
                for (int i = 0; i < idOrder.size() && i < retrievedImageIdList.size(); i++) {
                    idMap.put(idOrder.get(i), retrievedImageIdList.get(i));
                }
                // 替换
                matcher = pattern.matcher(ragflowContent);
                StringBuffer sb = new StringBuffer();
                while (matcher.find()) {
                    String num = matcher.group(1);
                    String imageIdVal = idMap.getOrDefault(num, "");
                    String imgTag = "";
                    if (!imageIdVal.isEmpty()) {
                        imgTag = "<img src='http://localhost/v1/document/image/" + imageIdVal + "' style='width:220px; display:block; border-radius:8px; margin:16px auto;' />";
                    }
                    matcher.appendReplacement(sb, Matcher.quoteReplacement(imgTag));
                }
                matcher.appendTail(sb);
                answer = sb.length() > 0 ? sb.toString() : ragflowContent;
                imageIdList = retrievedImageIdList;
//                System.out.println("[文本分支] ragflowContent: " + ragflowContent);
//                System.out.println("[文本分支] 提取到的关键词: " + extractedKeywords);
//                System.out.println("[文本分支] docIdList: " + docIdList);
//                System.out.println("[文本分支] retrievedImageIdList: " + retrievedImageIdList);
//                System.out.println("[文本分支] answer: " + answer);
            } catch (Exception e) {
                answer = "知识库检索异常: " + e.getMessage();
            }
        }

        // 保存到history1
        History1Entity msg = new History1Entity();
        msg.setChatId(chatId);
        msg.setUserId(userId);
        msg.setQuestion(question);
        msg.setAnswer(answer);
        msg.setImageUrl(imageUrl);
        msg.setCreateTime(LocalDateTime.now());
        history1Repository.save(msg);

        // 返回给前端
        ChatMessageDTO dto = new ChatMessageDTO();
        dto.question = question;
        dto.answer = answer;
        dto.imageUrl = imageUrl;
        dto.docId = imageId;
        dto.ocrText = ocrText;
        dto.imageIdList = imageIdList;
//        System.out.println("[最终返回] answer: " + answer);
//        System.out.println("[最终返回] imageIdList: " + imageIdList);
//        System.out.println("[最终返回] docId: " + imageId);
        return dto;
    }
    //删除会话接口
    @Transactional
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> deleteChat(@PathVariable Long id) {
        // 先删除history1表中该chatId的所有聊天记录
        history1Repository.deleteByChatId(id);
        // 再删除chat表中的会话
        chatRepository.deleteById(id);
        return ResponseEntity.ok().build();
    }

    // 图片上传接口（可选，前端如需单独上传图片）
    @PostMapping("/uploadImage")
    public Map<String, Object> uploadImage(@RequestParam("image") MultipartFile image) {
        Map<String, Object> result = new HashMap<>();
        try {
            ImageEntity img = new ImageEntity();
            img.setName(image.getOriginalFilename());
            img.setContentType(image.getContentType());
            img.setData(image.getBytes());
            img.setCreateTime(LocalDateTime.now());
            ImageEntity saved = imageRepository.save(img);
            result.put("id", saved.getId());
            result.put("url", "/api/chat/image/" + saved.getId());
        } catch (Exception e) {
            result.put("error", "图片上传失败");
        }
        return result;
    }

    // 图片获取接口
    @GetMapping("/image/{id}")
    public ResponseEntity<byte[]> getImage(@PathVariable Long id) {
        Optional<ImageEntity> imgOpt = imageRepository.findById(id);
        if (imgOpt.isPresent()) {
            ImageEntity img = imgOpt.get();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(img.getContentType()));
            return new ResponseEntity<>(img.getData(), headers, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    // 图片获取接口（通过ragflow image_id）
    @GetMapping("/image/imageid/{imageId}")
    public ResponseEntity<byte[]> getImageByImageId(@PathVariable String imageId) {
        // 这里假设本地数据库没有image_id字段，直接代理ragflow图片接口
        String url = "http://localhost/v1/document/image/" + imageId;
        RestTemplate restTemplate = new RestTemplate();
        try {
            ResponseEntity<byte[]> resp = restTemplate.getForEntity(url, byte[].class);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG); // 可根据实际类型调整
            return new ResponseEntity<>(resp.getBody(), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
} 